/**************************************************************************/
/*                                                                        */
/* Copyright (c) 2017 KYE Company                                         */
/* 跨越速运集团有限公司版权所有                                             */
/*                                                                        */
/* PROPRIETARY RIGHTS of KYE Company are involved in the                  */
/* subject matter of this material. All manufacturing, reproduction, use, */
/* and sales rights pertaining to this subject matter are governed by the */
/* license agreement. The recipient of this software implicitly accepts   */
/* the terms of the license.                                              */
/* 本软件文档资料是跨越速运集团有限公司的资产，任何人士阅读和                  */
/* 使用本资料必须获得相应的书面授权，承担保密责任和接受相应的法律约束。         */
/*                                                                        */
/**************************************************************************/

package com.foxsteps.gsonformat.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * JsonUtils
 *
 * @author 602595
 * @date 2023年02月17日 11:32
 */
public class JsonUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtils.class);
    private static ObjectMapper mapper = new ObjectMapper();
    private static ObjectMapper ignoreNullMapper = new ObjectMapper();
    static {
        recreateInnerObjectMapper(new HashMap<>());
        ignoreNullMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        ignoreNullMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

    public static void initObjectMapper(ObjectMapper objectMapper, Map<String, Object> jsonProperties) {

        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

        Boolean ignoreNull = (Boolean)jsonProperties.get("ignoreNull");
        if(ignoreNull != null && ignoreNull) {
            objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        }
    }

    public static synchronized void recreateInnerObjectMapper(Map<String, Object> jsonProperties) {
        ObjectMapper objectMapper = new ObjectMapper();
        initObjectMapper(objectMapper, jsonProperties);
        mapper = objectMapper;
    }

    public static String deserializer(Object json) {
        if (json == null) {
            return null;
        }
        try {
            return mapper.writeValueAsString(json);
        } catch (JsonProcessingException e) {
            LOGGER.error(e.getMessage());
            return null;
        }
    }


    public static ObjectMapper getMapper() {
        return mapper;
    }
}